import { createReducer } from 'reduxsauce';
import { REHYDRATE } from 'redux-persist/es/constants'

import {
  ADD_PATIENT_MESSAGE,
  ENTER_PATIENT_SESSION,
  PRE_ADD_PATIENT_MESSAGE,
  GET_PATIENT_MESSAGES,
  GET_PATIENT_MESSAGE_BY_ID,
  CLEAR_PATIENT_MESSAGE,
  GET_ACTIVE_SESSION,
  UPDATE_AUDIO_MSG_TEXT,
  SET_AUDIO_PLAYED,
  UPDATE_SURVEY_STATUS,
  UPDATE_ENTITYSTATUS_STATUS,
} from '@ACTIONS/chat'
import { ADD_COMMENT } from '@ACTIONS/comment'
import { DEFAULT_TAKE } from '@CONSTANTS/common'
import { MESSAGE_TYPE, PATIENT_CAN_SEND_COUNT } from '@CONSTANTS/chat'
import { PARTICIPANTS_TYPE } from '@CONSTANTS/consultation'

const INITIAL_STATE = {
  messages: [],
  currentSessionId: '',
  loadingMessages: false,
  currentSession: null,
  participants: null,
  patientCanSendCount: PATIENT_CAN_SEND_COUNT.SHOW_INPUT,
  activeConsultationSession: null,
}
const rehydrate = (state, { payload }) => {
  if (payload && payload.chat) {
    return { ...INITIAL_STATE, ...payload.chat }
  }
  return { ...state }
}

export default createReducer(INITIAL_STATE, {
  [REHYDRATE]: rehydrate,
  [ENTER_PATIENT_SESSION.FAILURE]: (state, { error }) => ({
    ...state,
    error,
    loadingMessages: false
  }),
  [ENTER_PATIENT_SESSION.REQUEST]: (state, { SessionId }) => {
    if (state.currentSessionId === SessionId) return state
    return {
      ...state,
      messages: [],
      loadingMessages: true,
      currentSessionId: '',
      currentSession: null,
      participants: null,
      patientCanSendCount: PATIENT_CAN_SEND_COUNT.SHOW_INPUT,
    }
  },
  [ENTER_PATIENT_SESSION.SUCCESS]: (state, { session, participants }) => {
    return ({
      ...state,
      currentSessionId: session.SessionId,
      currentSession: session,
      participants,
      loadingMessages: false,
      messages: session.LatestMessages,
      patientCanSendCount: session.LatestMessages?.[0]?.patientCanSendCount,
      loadEarlierMsg: session.LatestMessages.length >= DEFAULT_TAKE
    })
  },
  [GET_PATIENT_MESSAGES.REQUEST]: state => ({
    ...state,
    loadingMessages: true
  }),
  [GET_PATIENT_MESSAGES.FAILURE]: (state, { error }) => ({
    ...state,
    loadingMessages: false,
    error
  }),
  [GET_PATIENT_MESSAGES.SUCCESS]: (state, { list }) => ({
    ...state,
    messages: state.messages.concat(list),
    loadingMessages: false,
    loadEarlierMsg: list.length === DEFAULT_TAKE
  }),
  [PRE_ADD_PATIENT_MESSAGE.SUCCESS]: (state, { message }) => ({
    ...state,
    messages: [message].concat(state.messages)
  }),
  [GET_PATIENT_MESSAGE_BY_ID.SUCCESS]: (state, { message }) => {
    return ({
      ...state,
      messages: [message].concat(state.messages),
      patientCanSendCount: message?.patientCanSendCount,
    })
  }
  ,
  [ADD_PATIENT_MESSAGE.FAILURE]: (state, { falureMsg, resend }) => {
    const newMsg = falureMsg
    newMsg.failure = true
    if (!resend) {
      return {
        ...state,
        messages: [newMsg].concat(state.messages.filter(item => item.failure || !item.preView))
      }
    }
    return state
  },
  [ADD_PATIENT_MESSAGE.SUCCESS]: (state, { newMsg, preViewId }) => {
    const { Message } = newMsg
    function filterMessage(msg) {
      return msg._id !== Message._id && msg._id !== preViewId && !msg.preView
    }
    return {
      ...state,
      messages: [Message].concat(state.messages.filter(filterMessage)),
      patientCanSendCount: Message?.patientCanSendCount,
      newMessage: newMsg
    }
  },
  [CLEAR_PATIENT_MESSAGE.REQUEST]: state => ({
    ...state,
    patientCanSendCount: 0,
    messages: [],
    currentSession: null,
    currentSessionId: null,
    participants: null
  }),

  [ADD_COMMENT.SUCCESS]: (state, { data = {} }) => {
    const { ItemInfo: { ItemId }, Score, Comment } = data
    const { currentSession, messages, participants } = state
    if (!currentSession) {
      return state
    }
    const { EntityId, existComment } = currentSession || {}
    const self = participants.filter(item => item?.role === PARTICIPANTS_TYPE.Patient)[0] || {}
    const existOldComments=messages.findIndex(i =>{
      return i.entityId === ItemId
    })
    const newRating={
      MessageType: MESSAGE_TYPE.Rating,
      Score,
      createdAt: Date.now(),
      text: Comment,
      _id: `${ItemId}${MESSAGE_TYPE.Rating}`,
      user: {
        ...self,
        _id: self.uid
      }
    }
    if(existOldComments !== -1 ) { messages.splice(existOldComments,1,newRating) }
    return {
      ...state,
      currentSession: {
        ...currentSession,
        existComment: EntityId === ItemId ? true : existComment
      },
      messages: existOldComments === -1 ? [newRating, ...messages] : messages
    }
  },

  [UPDATE_AUDIO_MSG_TEXT.SUCCESS]: (state, { params: { audioText, _id } = {} }) => {
    const { currentSession, messages } = state
    if (!currentSession || !_id) {
      return state
    }
    return {
      ...state,
      messages: messages.map(item => (item._id === _id ? { ...item, patientPlayedAudio: true, audioText } : item))
    }
  },
  [UPDATE_AUDIO_MSG_TEXT.FAILURE]: (state, { error }) => ({
    ...state,
    error
  }),

  [SET_AUDIO_PLAYED.SUCCESS]: (state, { id }) => ({
    ...state,
    messages: state.messages.map(item => (item._id === id ? { ...item, patientPlayedAudio: true } : item))
  }),
  [UPDATE_SURVEY_STATUS.SUCCESS]: (state, { sId, status }) => ({
    ...state,
    messages: state.messages.map(item => (item.entityId === sId ? { ...item, SurveyStatus: status } : item))
  }),
  [SET_AUDIO_PLAYED.FAILURE]: (state, { error }) => ({
    ...state,
    error
  }),
  [UPDATE_ENTITYSTATUS_STATUS.SUCCESS]: (state, { entityId, status }) => ({
    ...state,
    messages: state.messages.map(item => (item.entityId === entityId ? { ...item, EntityStatus: status } : item))
  }),
})

